#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
        if (n == 1) return { 0 };
        vector<set<int>> link = vector<set<int>>(n);
        vector<bool> vis(n, false);
        vector<int> res;
        queue<int> q;
        for (const auto& vec : edges)
        {
            link[vec[0]].insert(vec[1]);
            link[vec[1]].insert(vec[0]);
        }
        for (int i = 0; i < n; i++)
        {
            if (link[i].size() == 1)
                q.push(i);
        }
        int past = 0;
        while (n - past > 2 && q.size())
        {
            int k = q.size();
            while (k--)
            {
                int node = q.front(); q.pop();
                vis[node] = true;
                for (const auto& e : link[node])
                {
                    link[e].erase(node);
                    if (!vis[e] && link[e].size() == 1)
                    {
                        q.push(e);
                        vis[e] = true;
                    }
                }
                ++past;
            }
        }
        while (q.size())
        {
            int node = q.front(); q.pop();
            res.push_back(node);
        }
        return res;
    }
};